/**
 * 满减不参与积分折扣
 * 满减的不参与优惠券使用
 * 满减 不参与 vip 等折扣
 * 满减送只支持单单卖的产品,一个商品只支持参加一个满减活动
 * */
import utils from '../../utils/util';
import WxValidate from '../../utils/WxValidate';
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    isShow: {
      type: Boolean,
      value: false
    },
    socialRoomId: {
      type: Number,
      default: 0
    },
    addrId: { //收货地址id
      type: Number,
      default: 0,
      observer: function () {
        this.setAddrInfo();
      }
    },
    detailId: {
      type: Number,
      default: 0
    },
    isOpenAppletSubMch: {
      type: Boolean,
      default: true
    },
    params: {
      type: Object,
      value: {},
      observer: function (val) {
        // val.gsiiId =  val.gsiiId || null
        console.log("params-val", val)
      }
    }
  },
  lifetimes: {
    attached: function () {
      // this._payType = 0; //0是微信支付，1是余额支付，2是虚拟币支付
      this._companyShare = wx.getStorageSync('companyShare');
      this._userSecret = wx.getStorageSync('userSecret')
      console.log("_companyShare", this._companyShare.companyAuth.companyName, this._userSecret);
    },
  },

  /**
   * 组件的初始数据
   */
  data: {
    tabList: [{
      title: "物流分配",
      idx: 1
    }, {
      title: "线下自提",
      idx: 2
    }],
    tabIndex: 1,
    addressInfo: "", //收货地址信息
    isMallExpressDeliver: -1, // 是否是物流
    isMallOfflineDeliver: -1, //是否允许线下自提
    totalPostage: null, //需要支付总邮费
    totalPrice: 0, //总的价格
    totalDiscountPrice: 0, //折扣后的价格
    goodInfo: {}, //选中的商品的信息
    isCanUseCoupon: false, //是否可以使用优惠券
    isCanUsePoint: false, //是否可以使用积分
    isChooseUsePoint: false, //是否选择使用积分抵扣
    vipType: -1,
    couponList: [], //优惠券列表
    isShowCouponList: false,
    chooseCouponInfo: null, //选中优惠券的价格
    // chooseCouponId: -1, //选中的优惠券的id
    chooseCouponPrice: 0, //优惠券金额

    disCountPriceInfo: "", //vip的折扣价格
    quantity: 1, //购买的数量
    remarksMsg: "", //商家留言
    isCanUseFullDecre: false, //是否可是使用满减
    cashBack: {}, //满减活动
    currCashBackItem: {}, //当前满减活动的选项
    isShowFullDecreIntro: false, //是否显示满减的介绍弹框
    isInvoice: false, //是否需要开发票

    isShowInvoiceForm: false, //是否显示开票表单
    invoiceType: 2, //1开  2不开
    invoiceTypeForForm: 2, //1开  2不开
    invoiceHeadType: 1, //1个人  2公司
    pointDiscountText: "", //积分抵扣文字
    offlineAddressInfo: null, //线下提货地址信息
    offlineUserInfo: null, //线下提货个人信息
    isShowSelfpickUserForm: false, //线下提货个人信息表单是否显示
    isShowSelfpickSite: false, //是否显示自提收货地址
    isShowSelfpickArea: false, //是否显示区域选择弹框
    email: "",
    isChooseAgreement: true, //选中协议

  },

  /**
   * 组件的方法列表
   */
  methods: {
    onOpen() {
      this._companyShare = wx.getStorageSync('companyShare');
      this._invoiceHeadInfo = {}; //开票的信息
      this._isSubmitRequesting = false;
      // this._email = ""; //邮箱
      this._pointDeductNum = 0; //积分抵扣的数量
      this._pointDeductPrice = 0; //积分抵扣的金钱
      this._fullDecreGiveProList = []; //满减赠送商品
      this._submitType = 1; //判断商品购买类型 4:拼团 2:限时购 1:普通商品, 活动类型(抽奖福利大转盘等)就是活动的type
      let sendData = {
        mgId: this.data.params.mgId,
      }
      /*
       *  ┌─────────────────────────────────────────────────────────────┐
       *  @@@ 直播购买下单，非活动（大转盘、抽奖、福利等）下单参数设置-start
       *  └─────────────────────────────────────────────────────────────┘
       */
      if (!this.data.params.query || !this.data.params.query.fromType) {
        sendData.isLive = 1;
        sendData.socialRoomId = this.data.socialRoomId;
        if (this.data.detailId) {
          sendData.detailId = this.data.detailId;
        }
      }
      /*
       *  ┌─────────────────────────────────────────────────────────────┐
       *  @@@ 直播购买下单，非活动（大转盘、抽奖、福利等）下单参数设置-end
       *  └─────────────────────────────────────────────────────────────┘
       */
      this.setData({
        email: "",
        remarksMsg: "",
        pointDiscountText: "",
        chooseCouponPrice: "",
        couponList: [],
        offlineAddressInfo: null,
        currCashBackItem: {},
        cashBack: "",
        tabIndex: 1,
        invoiceType: 2,
        invoiceHeadType: 1,
        invoiceTypeForForm: 2,
        quantity: 1, //购买的数量
        isMallExpressDeliver: -1,
        chooseCouponInfo: null
      })

      Promise.all([this._getSubOrderPage(), this._getGoodDetail(sendData)]).then((values) => {
        console.log("values", values);
        this._orderInfo = values[0];
        this._gdInfo = values[1];
        //赋值
        this._flashSales = this._gdInfo.flashSales;
        this._cashBack = this._gdInfo.cashBack;
        this._freeShipping = this._gdInfo.freeShipping;
        this._specItemInfos = this._gdInfo.specItemInfos;
        this._specItems = this._gdInfo.specItems;
        this._goods = this._gdInfo.goods;
        this._banners = this._gdInfo.banners;
        this._agentConfs = this._gdInfo.agentConfs;
        let goodInfo = this._gdInfo.goods;
        //传递规格参数规格
        if (this.data.params.gsiiId) {
          let specInfo = this.getSpecsParamsById(this.data.params.gsiiId);
          goodInfo.specStr = this.getSpecsStr(JSON.parse(specInfo.itemGroup));
          goodInfo = {
            ...goodInfo,
            ...specInfo
          }
          this._goods.price = goodInfo.price;
        }
        goodInfo.coverImg = goodInfo.gsiPicture || goodInfo.avatar || this._banners[0].url;
        this.data.quantity = this.data.params.quantity;
        this.data.couponList = this._orderInfo.user.coupon
        this.data.isCanUseFullDecre = this.isCanUseFullDecre(Number(this._goods.price).toFixed(2) * this.data.quantity);
        this.data.disCountPriceInfo = this.getDisPriceInfo();
        this.data.isCanUseCoupon = this.isCanUseCoupon(Number(this._goods.price).toFixed(2) * this.data.quantity);
        this.data.isCanUsePoint = this.isCanUsePoint();
        /*
         *  ┌─────────────────────────────────────────────────────────────┐
         *  @@@ 活动（大转盘、抽奖、福利等）下单参数充值，不允许使用优惠券等-start
         *  └─────────────────────────────────────────────────────────────┘
         */
        if (this.data.params.query && this.data.params.query.fromType) {
          goodInfo.stock = 1;
          goodInfo.price = 0;
          this.data.isCanUseFullDecre = false;
          this.data.disCountPriceInfo = null;
          this.data.isCanUseCoupon = false;
          this.data.isCanUsePoint = false;
          this._submitType = this.data.params.query.fromType;
          this._submitRid = this.data.params.query.rId;
          this._submitTalId = this.data.params.query.prizeId;
        }
         /*
         *  ┌─────────────────────────────────────────────────────────────┐
         *  @@@ 活动（大转盘、抽奖、福利等）下单参数充值，不允许使用优惠券等-end
         *  └─────────────────────────────────────────────────────────────┘
         */

        this.setData({
          goodInfo: goodInfo,
          cashBack: this._cashBack,
          isCanUseCoupon: this.data.isCanUseCoupon,
          isCanUsePoint: this.data.isCanUsePoint,
          isCanUseFullDecre: this.data.isCanUseFullDecre,
          couponList: this.data.couponList,
          // totalPostage: this._goods.postage * 1,
          totalPostage: this._orderInfo.postage,
          quantity: this.data.params.quantity,
          disCountPriceInfo: this.data.disCountPriceInfo,
          isInvoice: this._orderInfo.isInvoice,
          isMallExpressDeliver: this._goods.isMallExpressDeliver,
          isMallOfflineDeliver: this._goods.isMallOfflineDeliver,
          tabIndex: (this._goods.isMallExpressDeliver == -1 && this._goods.isMallOfflineDeliver == 1) ? 2 : 1,
        }, () => {
          this.calcProPrice();
        });
      })
      this._getVipType().then(res => {
        this.setData({
          vipType: res.vipType
        })
      })
      this.setAddrInfo();
    },
    toggleAgreement() {
      this.setData({
        isChooseAgreement: !this.data.isChooseAgreement
      })
    },
    //提交订单
    submitOrder() {
      if (this._isSubmitRequesting) return;
      //如果是活动领奖 && 没有开通二级商户 &&  非自提 && 有运费
      console.log(this.data.isOpenAppletSubMch, this.data.params.query, this.data.isMallExpressDeliver, this.data.tabIndex, this.data.totalPostage)

      /*
       *  ┌─────────────────────────────────────────────────────────────┐
       *  @@@ 活动（大转盘、抽奖、福利等）提交判断-start
       *  └─────────────────────────────────────────────────────────────┘
      */
      if (this.data.params.query && this.data.params.query.fromType) {
        //抽奖活动的下单
        if ((!this.data.isOpenAppletSubMch && this.data.isMallExpressDeliver == 1 && this.data.tabIndex == 1 && this.data.totalPostage || this._gdInfo.isRelForm)) {
          //运费快递的时候（涉及支付），快下二级商户有没有开通 || 关联表单
          this.selectComponent("#attendGuide").show();
          return;
        }
      }
      /*
       *  ┌─────────────────────────────────────────────────────────────┐
       *  @@@ 活动（大转盘、抽奖、福利等）提交判断-end
       *  └─────────────────────────────────────────────────────────────┘
      */
      if (!this.data.isChooseAgreement) {
        wx.showToast({
          title: '请先勾选协议！',
          icon: "none"
        })
        return;
      }
      let deliverType = this._getDeliverType();
      if (this._goods.isMail == 1) {
        if (!this.data.email || !/^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/.test(this.data.email)) {
          wx.showToast({
            title: '请输入正确的邮箱',
            icon: "none"
          })
          return;
        }
      }
      if (deliverType == 2) {
        if (!this.data.offlineAddressInfo) {
          wx.showToast({
            title: '请选择自提点',
            icon: "none"
          })
          return;
        }
        if (!this.data.offlineUserInfo) {
          wx.showToast({
            title: '请填写提货人信息',
            icon: "none"
          })
          return;
        }
      }
      this._isSubmitRequesting = true;

      let goods = [{
        mgId: this.data.params.mgId,
        quantity: this.data.quantity,
        gsiiId: this.data.params.gsiiId || null,
        postage: deliverType == 1 ? this.data.totalPostage : 0,
        deductedPoints: this._pointDeductNum,
        deductedMoney: this._pointDeductPrice,
        amount: this.data.totalDiscountPrice,
        subSpecs: '',
        type: 1,
        pId: "",
        isMallExpressDeliver: deliverType == 1 ? 1 : -1,
        isMallOfflineDeliver: deliverType == 2 ? 1 : -1,
        relData: this._goods.relData
      }];

      let deductedCouponPrice = 0;
      if (!this.data.isCanUseFullDecre && this.data.chooseCouponInfo) {
        if (this.data.chooseCouponInfo.price <= this.data.totalDiscountPrice) {
          deductedCouponPrice = this.data.chooseCouponInfo.price;
        } else {
          deductedCouponPrice = this.data.totalDiscountPrice;
        }
      }
      let data = {
        mail: this.data.email || '', //邮箱
        goId: null,
        msg: this.data.remarksMsg, //商家留言
        buyNow: true,
        payMoney: this.data.totalPrice,
        userAddressId: this.data.addressInfo.addrId,
        deductedPoints: this._pointDeductNum, //抵扣的积分数量
        deductedMoney: this._pointDeductPrice,
        deductedCouponPrice: deductedCouponPrice,
        postage: deliverType == 1 ? this.data.totalPostage : 0,
        goods: goods,
        invoiceTitle: this.data.invoiceType == 1 ? (this.data.invoiceHeadType == 1 ? '个人' : '公司') : '',
        invoiceMsg: this._invoiceHeadInfo.invoiceName || "",
        invoiceCode: this._invoiceHeadInfo.invoiceCode || "",
        type: this._submitType,
        useCoupon: (!this.data.isCanUseFullDecre && this.data.chooseCouponInfo) ? this.data.chooseCouponInfo.rcdId : '',
        payMethod: 1,
        userName: deliverType == 1 ? this.data.addressInfo.name : this.data.offlineAddressInfo.name,
        userMobile: deliverType == 1 ? this.data.addressInfo.mobile : this.data.offlineAddressInfo.mobile,
        modId: deliverType == 1 ? '' : this.data.offlineAddressInfo.modId,
        deliverType: deliverType,
        cashBackAmount: this.data.currCashBackItem.reducePrice || 0,
        relData: this._goods.relData,
        palId: ''
      }
      /*
       *  ┌─────────────────────────────────────────────────────────────┐
       *  @@@ 直播购买下单，非活动（大转盘、抽奖、福利等）下单参数设置-start
       *  └─────────────────────────────────────────────────────────────┘
       */
      if (!this.data.params.query || !this.data.params.query.fromType) {
        data.subProdType = 51;
        data.subProdId = this.data.socialRoomId;
      }
      /*
       *  ┌─────────────────────────────────────────────────────────────┐
       *  @@@ 直播购买下单，非活动（大转盘、抽奖、福利等）下单参数设置-start
       *  └─────────────────────────────────────────────────────────────┘
       */
      // 符合满减活动的赠送商品，将商品数据存入goods
      if (this.isCanUseFullDecre && this._fullDecreGiveProList.length) {
        this._fullDecreGiveProList.forEach((item => {
          goods.push({
            mgId: item.prodId,
            quantity: this.data.quantity > item.stock ? item.stock : this.data.quantity,
            gsiiId: item.gsiiId || null,
            postage: deliverType == 1 ? item.postage : 0,
            deductedPoints: 0,
            deductedMoney: 0,
            amount: 0,
            subSpecs: item.shopSpecInfo || '',
            type: 1,
            pId: item.pId,
            isMallExpressDeliver: deliverType == 1 ? 1 : -1,
            isMallOfflineDeliver: deliverType == 2 ? 1 : -1,
            isGift: 1,
            relData: item.relData || []
          })
        }))
      }
      if (this._submitRid) {
        data.rId = this._submitRid;
      }
      if (this._submitTalId) {
        data.talId = this._submitTalId;
      }
      utils.post('goodsOrders/submitOrder', data, true, 1).then(res => {
        if (res.orderId == -1) {
          wx.showModal({
            title: '提示',
            content: '订单提交失败，请重新提交！',
            showCancel: false,
            confirmText: "我知道"
          })
          this._isSubmitRequesting = false;
        } else if (res.code == 201) {
          wx.showToast({
            title: '支付成功',
            icon: "success",
            duration:2500
          })
          this._isSubmitRequesting = false;
          this.setData({
            isShow: false
          });
          this.triggerEvent("submitSuccess")
        } else {
          utils.post("payment/wxpayConf", {
            openid: this._userSecret.openId,
            goId: res.orderId
          }).then(resData => {
            wx.navigateTo({
              url: '/pages/commerce-pay/index',
              success: (res) => {
                res.eventChannel.emit('acceptDataFromOpenerPage', {
                  timeStamp: resData.data.timeStamp,
                  nonceStr: resData.data.nonceStr,
                  package: resData.data.package,
                  signType: resData.data.signType,
                  paySign: resData.data.paySign
                })
              },
              complete: () => {
                this._isSubmitRequesting = false;
              }
            });
          }).catch(() => {
            this._isSubmitRequesting = false;
          })
        }
      }).catch(() => {
        this._isSubmitRequesting = false;
      })
    },

    ////1物流 2线下自提 3物流+线下
    _getDeliverType() {
      let res = 1;
      let goods = this._goods;
      if (goods.isMallExpressDeliver == 1 && goods.isMallOfflineDeliver == 1) {
        //物流+线下
        if (this.data.tabIndex == 2) {
          res = 2
        }
      } else if (goods.isMallExpressDeliver == -1 && goods.isMallOfflineDeliver == 1) {
        //线下自提
        res = 2
      }
      console.log("_getDeliverType", res);
      return res;
    },




    openSelfpickSite() {
      this.setData({
        isShowSelfpickSite: true
      })
    },
    openSelfpickArea() {
      this.setData({
        isShowSelfpickArea: true
      })
    },
    openSelfpickUserForm() {
      if (!this._selfpickUserFormValidate) {
        this._initSelfpickUserFormValidate();
      }
      this.setData({
        isShowSelfpickUserForm: true
      })
    },
    selfpickUserFromSubmit(e) {
      let params = e.detail.value;
      if (!this._selfpickUserFormValidate.checkForm(params)) {
        const error = this._selfpickUserFormValidate.errorList[0];
        wx.showToast({
          title: error.msg,
          icon: "none"
        })
        return;
      }
      this.setData({
        isShowSelfpickUserForm: false,
        offlineUserInfo: params
      })
    },
    //
    chooseSelfPickArea(e) {
      console.log("chooseSelfPickArea", e);
      this.setData({
        offlineAddressInfo: e.detail
      })
    },
    //开票
    switchInvoiceType(e) {
      let idx = e.currentTarget.dataset.idx;
      this.setData({
        invoiceTypeForForm: idx
      });
      this._initInvoiceValidate();
    },
    //开票
    switchInvoiceHeadType(e) {
      let idx = e.currentTarget.dataset.idx;
      this.setData({
        invoiceHeadType: idx
      });
      this._initInvoiceValidate();
    },
    invoiceFormSubmit(e) {
      let params = e.detail.value;
      if (this.data.invoiceTypeForForm == 1) {
        if (!this._invoiceValidate.checkForm(params)) {
          const error = this._invoiceValidate.errorList[0];
          wx.showToast({
            title: error.msg,
            icon: "none"
          })
          return;
        }
      }
      console.log("params", params)
      this._invoiceHeadInfo = params;
      this.setData({
        isShowInvoiceForm: false,
        invoiceType: this.data.invoiceTypeForForm,
      })
    },


    openFullDecreIntro() {
      this.setData({
        isShowFullDecreIntro: true
      })
    },
    openInvoiceForm() {
      this.setData({
        isShowInvoiceForm: true
      })
    },
    /**
     * 满减活动满足 就不参与使用积分  
     * 砍价不参与积分
     * 拼团 限时购不参与积分抵扣
     * */
    isCanUsePoint() {
      let flag = true;
      let orderInfo = this._orderInfo;
      let price = Number(this._goods.price).toFixed(2) * this.data.quantity;
      let isCanUseFullDecre = this.data.isCanUseFullDecre;
      console.log(orderInfo, orderInfo.user.points >= orderInfo.rmb2Points, Math.floor(Number(orderInfo.user.points) / Number(orderInfo.rmb2Points)))
      //参加满减不使用积分抵扣
      if (isCanUseFullDecre) {
        flag = false;
      }
      if (orderInfo.rmb2Points && orderInfo.user.points < orderInfo.rmb2Points) {
        flag = false;
      }
      if (this._goods.pointsDeduct * 1 <= 0) {
        flag = false
      }
      console.log("isCanUsePoint", flag)
      return flag;
    },

    switchUsePoint(e) {
      console.log(e)
      let val = e.detail.value;
      this.setData({
        isChooseUsePoint: val
      }, () => {
        this.calcProPrice();
      })
    },
    inputNumberChange(e) {
      console.log("e", e);
      let quantity = e.detail;
      this.data.quantity = quantity;
      this.data.isCanUseFullDecre = this.isCanUseFullDecre(Number(this._goods.price).toFixed(2) * quantity);
      this.data.disCountPriceInfo = this.getDisPriceInfo();
      this.data.isCanUseCoupon = this.isCanUseCoupon(Number(this._goods.price).toFixed(2) * quantity);
      this.data.isCanUsePoint = this.isCanUsePoint();
      this.setData({
        quantity: this.data.quantity,
        disCountPriceInfo: this.data.disCountPriceInfo,
        isCanUseFullDecre: this.data.isCanUseFullDecre,
        isCanUseCoupon: this.data.isCanUseCoupon,
        isCanUsePoint: this.data.isCanUsePoint
      }, () => {
        this.calcProPrice();
      })
    },
    //
    bindRemarksMsg(e) {
      this.setData({
        remarksMsg: e.detail.value
      })
    },

    bindEmailInput(e) {
      this.setData({
        email: e.detail.value
      })
    },

    //计算总价格
    calcProPrice() {
      let price = Number(this._goods.price).toFixed(2) * this.data.quantity;
      price = this.getAfterDiscountPrice(price);
      if (this.data.isCanUseFullDecre) {
        price = this.getAfterFullDecrePrice(price)
      }
      if (this.data.isCanUseCoupon) {
        price = this.getAfterCouponPrice(price);
      }
      price = this.getAfterPointsPrice(price);
      let deliverType = this._getDeliverType();
      price = (price * 1 + (deliverType == 1 ? this.data.totalPostage : 0) * 1).toFixed(2);
      this.setData({
        totalPrice: price
      })
    },
    //使用优惠券后的价格
    getAfterCouponPrice(price) {
      console.log("getAfterCouponPrice", typeof (price))
      let info = this.data.chooseCouponInfo;
      if (info) {
        price = price - info.price;
        price = price > 0 ? price.toFixed(2) : '0.00';
      }
      console.log("getAfterCouponPrice", price);
      return price;
    },
    //
    getAfterFullDecrePrice(price) {
      let cashBack = this._cashBack;
      let contents = cashBack.contents;
      let len = contents.length;
      let quantity = this.data.quantity;
      let currCashBackItem = null;
      if (cashBack.backType == 1) {
        //满N元
        if (cashBack.ruleType == 1) {
          //N元阶梯满减
          for (let i = len - 1; i >= 0; i--) {
            if (price >= contents[i].thresholdAmount) {
              currCashBackItem = contents[i];
              break;
            }
          }
          if (currCashBackItem.discountType == 1) {
            //满多少间多少金额
            currCashBackItem.reducePrice = currCashBackItem.backAmount
          } else if (currCashBackItem.discountType == 2) {
            //满多少折扣
            currCashBackItem.reducePrice = price * (1 - currCashBackItem.backDiscount * 1 / 100)
          }

          price = price - currCashBackItem.reducePrice;
          console.log("cashBackPrice", currCashBackItem)
        } else if (cashBack.ruleType == 2) {
          //循环满减(M)
          if (price > cashBack.contents[0].thresholdAmount) {
            currCashBackItem = cashBack.contents[0];
            currCashBackItem.reducePrice = Math.floor(price / currCashBackItem.thresholdAmount) * currCashBackItem.backAmount
            price = price - currCashBackItem.reducePrice
          }
        }
      } else {
        //满N件
        if (cashBack.ruleType == 1) {
          //N件阶梯满减
          for (let i = len - 1; i >= 0; i--) {
            if (quantity >= contents[i].thresholdAmount) {
              currCashBackItem = contents[i];
              break;
            }
          }
          if (currCashBackItem) {
            if (currCashBackItem.discountType == 1) {
              //满减金额
              currCashBackItem.reducePrice = currCashBackItem.backAmount
            } else if (currCashBackItem.discountType == 2) {
              //满多少折扣
              currCashBackItem.reducePrice = price * (1 - currCashBackItem.backDiscount * 1 / 100)
            }
            price = price - currCashBackItem.reducePrice;
          }
        } else {
          //N件循环满减（没有折扣）
          currCashBackItem = cashBack.contents[0];
          currCashBackItem.reducePrice = Math.floor(this.data.quantity / currCashBackItem.thresholdAmount) * currCashBackItem.backAmount
          price = price - currCashBackItem.reducePrice;
        }
      }
      console.log("currCashBackItem", currCashBackItem)
      if (currCashBackItem && currCashBackItem.isSendProd == 1) {
        this._fullDecreGiveProList = currCashBackItem.sendProdList || [];
      }
      this.setData({
        totalPostage: currCashBackItem.isFreeShipping == 1 ? 0 : this.data.totalPostage,
        currCashBackItem: currCashBackItem
      })
      price = price > 0 ? Number(price).toFixed(2) : '0.00';
      return price;
    },

    //或者满减赠送的商品数量（循环满减就是满几级赠送几个）


    //获取折扣信息
    getDisPriceInfo() {
      if (this.data.isCanUseFullDecre) return '';
      let goods = this._gdInfo.goods;
      let vipType = this._orderInfo.user.vipType;
      let res = "";
      if (vipType == 2) {
        //vip身份-折扣
        if (goods.vipDiscount && goods.vipDiscount != 100) {
          res = {
            dpVal: goods.vipDiscount,
            tit: `VIP折扣(${(goods.vipDiscount / 10).toFixed(2)}折)`,
            val: "￥" + (goods.price * goods.vipDiscount / 100).toFixed(2)
          }
        }
      } else if (vipType == 4) {
        //svip身份-折扣
        if (goods.svipDiscount && goods.svipDiscount != 100) {
          res = {
            dpVal: goods.svipDiscount,
            tit: `SVIP折扣(${(goods.svipDiscount / 10).toFixed(2)}折)`,
            val: "￥" + (goods.price * goods.svipDiscount / 100).toFixed(2)
          }
        }
      } else if (vipType == 3) {
        //代理商
        if (goods.agentDiscount && goods.agentDiscount != 100) {
          res = {
            dpVal: goods.agentDiscount,
            tit: "服务商折扣",
            val: "￥" + (goods.price * basicInfo.agentDiscount / 100).toFixed(2)
          }
        }
      } else if (vipType == 5) {
        //2级经销商
        if (this._companyShare.companyAuth && this._companyShare.companyAuth.agentLevels >= 2) {
          res = {
            dpVal: goods.partnerDiscount,
            tit: `${this._agentConfs.partnerName}(${(goods.partnerDiscount / 10).toFixed(2)}折)`,
            val: "￥" + (goods.price * goods.partnerDiscount / 100).toFixed(2)
          }
        }
      } else if (vipType == 6) {
        //3级经销商
        if (this._companyShare.companyAuth && this._companyShare.companyAuth.agentLevels >= 3) {
          res = {
            dpVal: goods.branchDiscount,
            tit: `${this._agentConfs.branchName}(${(goods.branchDiscount / 10).toFixed(2)}折)`,
            val: "￥" + (goods.price * goods.branchDiscount / 100).toFixed(2)
          }
        }
      } else if (vipType == 7) {
        //4级经销商
        if (this._companyShare.companyAuth && this._companyShare.companyAuth.agentLevels >= 4) {
          res = {
            dpVal: goods.cooDiscount,
            tit: `${this._agentConfs.cooName}(${(goods.cooDiscount / 10).toFixed(2)}折)`,
            val: "￥" + (goods.price * goods.cooDiscount / 100).toFixed(2)
          }
        }
      } else if (vipType == 8) {
        //5级经销商
        if (this._companyShare.companyAuth && this._companyShare.companyAuth.agentLevels >= 5) {
          res = {
            dpVal: goods.agencyDiscount,
            tit: `${this._agentConfs.agencyName}(${(goods.agencyDiscount / 10).toFixed(2)}折)`,
            val: "￥" + (goods.price * goods.agencyDiscount / 100).toFixed(2)
          }
        }
      } else if (vipType == 9) {
        //6级经销商
        if (this._companyShare.companyAuth && this._companyShare.companyAuth.agentLevels >= 6) {
          res = {
            dpVal: goods.agent6Discount,
            tit: `${this._agentConfs.agent6Name}(${(goods.agent6Discount / 10).toFixed(2)}折)`,
            val: "￥" + (goods.price * goods.agent6Discount / 100).toFixed(2)
          }
        }
      } else if (vipType == 10) {
        //7级经销商
        if (this._companyShare.companyAuth && this._companyShare.companyAuth.agentLevels >= 6) {
          res = {
            dpVal: goods.agent7Discount,
            tit: `${this._agentConfs.agent7Name}(${(goods.agent7Discount / 10).toFixed(2)}折)`,
            val: "￥" + (goods.price * goods.agent7Discount / 100).toFixed(2)
          }
        }
      } else if (vipType == 11) {
        //8级经销商
        if (this._companyShare.companyAuth && this._companyShare.companyAuth.agentLevels >= 6) {
          res = {
            dpVal: goods.agent8Discount,
            tit: `${this._agentConfs.agent8Name}(${(goods.agent8Discount / 10).toFixed(2)}折)`,
            val: "￥" + (goods.price * goods.agent8Discount / 100).toFixed(2)
          }
        }
      } else if (vipType == 12) {
        //9级经销商
        if (this._companyShare.companyAuth && this._companyShare.companyAuth.agentLevels >= 6) {
          res = {
            dpVal: goods.agent9Discount,
            tit: `${this._agentConfs.agent9Name}(${(goods.agent9Discount / 10).toFixed(2)}折)`,
            val: "￥" + (goods.price * goods.agent9Discount / 100).toFixed(2)
          }
        }
      }
      console.log("getDisPriceInfo", {
        vipType: vipType,
        ...res
      })
      if (res && parseInt(res.dpVal) != 100) {
        return {
          vipType: vipType,
          ...res
        }
      }
      return "";
    },

    //积分抵扣后的价格
    getAfterPointsPrice(price) {
      console.log("getAfterPointsPrice", typeof (price))
      let goodsInfo = this._goods,
        orderInfo = this._orderInfo;
      let maxPointsDiscountPrice = 0;
      maxPointsDiscountPrice = price > goodsInfo.pointsDeduct * 1 ? goodsInfo.pointsDeduct : price; //价格大于
      let pointToPirce = Math.floor(orderInfo.user.points) / orderInfo.rmb2Points;
      //积分抵扣金额
      let pointsDiscountPirce = pointToPirce > maxPointsDiscountPrice ? maxPointsDiscountPrice : pointToPirce;
      console.log("rmb2Points", pointsDiscountPirce, goodsInfo, orderInfo)
      //使用的积分数量
      let userPointNum = pointsDiscountPirce * orderInfo.rmb2Points;
      userPointNum = pointToPirce > maxPointsDiscountPrice ? Math.ceil(userPointNum) : Math.floor(userPointNum);
      this.setData({
        pointDiscountText: `${userPointNum}积分抵扣${(pointsDiscountPirce * 1).toFixed(2)}元`
      })
      if (this.data.isChooseUsePoint) {
        this._pointDeductNum = userPointNum;
        this._pointDeductPrice = (pointsDiscountPirce * 1).toFixed(2);
        price = price - pointsDiscountPirce;
        price = price > 0 ? price.toFixed(2) : '0.00';
      } else {
        this._pointDeductNum = 0;
        this._pointDeductPrice = 0;
      }
      console.log("getAfterPointsPrice", `price:${price}`);
      return price;
    },

    //打开优惠券列表
    openCouponList() {
      this.setData({
        isShowCouponList: true
      })
    },
    //选择优惠券
    chooseCoupon(e) {
      let data = e.detail;
      let price = this.getAfterDiscountPrice(this._goods.price * 1);
      console.log("chooseCoupon", data);
      if (data && data.type == 3) {
        if (data.amount * 1 > 0 && data.amount * 1 > price) {
          wx.showToast({
            title: '购买金额未达到要求，不可使用！',
            icon: "none",
            duration: 2500
          });
          return;
        }
      }
      this.setData({
        chooseCouponInfo: data
      }, () => {
        this.calcProPrice();
      });
    },

    //获取vip服务商代理商折扣后的价格
    getAfterDiscountPrice(price) {
      let vipInfo = this.data.disCountPriceInfo;
      if (vipInfo && vipInfo.vipType) {
        price = price * vipInfo.dpVal / 100
      }
      price = Number(price) > 0 ? Number(price).toFixed(2) : '0.00';
      this.setData({
        totalDiscountPrice: price
      })
      console.log("getAfterDiscountPrice", `price:${price}`)
      return price;
    },

    // 获取当前vipType在计算订单信息
    _getVipType() {
      return utils.get('redeemCodes/getVipType')
    },
    //获取商品详情
    _getGoodDetail(data) {
      return utils.get(`goods/goodsDetail`, data)
    },
    //获取订单信息
    _getSubOrderPage() {
      let params = this.data.params;
      return utils.post("goodsOrders/subOrderPage", {
        arrGodId: `[${params.mgId}]`,
        goodList: [{
          gsiiId: params.gsiiId || null,
          mgId: params.mgId,
          quantity: params.quantity
        }]
      }, true, 1)
    },
    //能否使用优惠券
    isCanUseCoupon() {
      let flag = false;
      if (this._companyShare.companyAuth.enableRedeemCode == 1) {
        //限时购/拼团/大转盘/支付有礼/砍价不参与优惠券购买   满减就不参与优惠券
        flag = true;
        if (this._gdInfo.turntableData || this._gdInfo.payAwardData) {
          flag = false
        } else if (this.data.isCanUseFullDecre) {
          flag = false;
        } else if (!this.data.couponList.length) {
          flag = false;
        }
      }
      console.log("isCanUseCoupon", flag)
      return flag;
    },
    isCanUseFullDecre(price) {
      let flag = false;
      let cashBack = this._cashBack;
      if (cashBack && cashBack.mcbId) {
        if (cashBack.backType == 1) {
          //满N元减/送
          if (cashBack.ruleType == 1) {
            //阶梯满减 (满多少 减多少元  满多少则扣多少)
            let currCashBackItem = cashBack.contents.reduce((prev, next) => {
              return prev.thresholdAmount < next.thresholdAmount ? prev : next
            })
            if (price >= currCashBackItem.thresholdAmount) {
              flag = true;
            }
          } else if (cashBack.ruleType == 2) {
            //循环满减(M)
            if (price >= cashBack.contents[0].thresholdAmount) {
              flag = true;
            }
          }
        } else {
          //满N件减/送
          if (cashBack.ruleType == 1) {
            //阶梯满减
            let currCashBackItem = cashBack.contents.reduce((prev, next) => {
              return prev.thresholdAmount < next.thresholdAmount ? prev : next
            })
            if (this.data.quantity >= currCashBackItem.thresholdAmount) {
              flag = true;
            }
          } else if (cashBack.ruleType == 2) {
            //循环满减(M)
            if (this.data.quantity >= cashBack.contents[0].thresholdAmount) {
              flag = true;
            }
          }
        }
      }
      console.log("isCanUseFullDecre", flag)
      return flag;
    },
    //获取选中规格的参数
    getSpecsParamsById(id) {
      let lists = this._specItemInfos || [];
      let res = {};
      for (let i = 0; i < lists.length; i++) {
        if (lists[i].gsiiId == id) {
          res = lists[i];
          break;
        }
      }
      console.log("getSpecsParamsById", res);
      return res;
    },
    //获取规格的字符串
    getSpecsStr(arr) {
      let specItems = this._specItems;
      let str = "";
      specItems.forEach((item) => {
        if (arr.includes(item.gsiId)) {
          str += item.name + " "
        }
      })
      return str;
    },
    openAddrList() {
      this.triggerEvent("openAddrList", {
        addrId: this.data.addressInfo ? this.data.addressInfo.addrId : ''
      })
    },
    switchTab(e) {
      console.log(e);
      let idx = e.currentTarget.dataset.idx;
      this.setData({
        tabIndex: idx
      }, () => {
        this.calcProPrice();
      })
    },


    setAddrInfo() {
      utils.get('address', {
        page: 1
      }).then(res => {
        let defaultAddr = "";
        let chooseItem = "";
        res.address.data.forEach(item => {
          if (this.data.addrId == item.addrId) {
            chooseItem = item;
          }
          if (item.status == 1) {
            defaultAddr = item;
          }
        });
        if (chooseItem) {
          defaultAddr = chooseItem;
        }
        if (!chooseItem && !defaultAddr && res.address.data.length) {
          defaultAddr = res.address.data[0];
        }
        this.setData({
          offlineUserInfo: {
            name: defaultAddr.name,
            mobile: defaultAddr.mobile
          },
          addressInfo: defaultAddr
        })
      })
    },

    _initInvoiceValidate() {
      let rules, messages;
      if (this.data.invoiceHeadType == 1) {
        rules = {
          invoiceName: {
            required: true
          }
        };
        messages = {
          invoiceName: {
            required: "请输入个人名字",
          }
        }
      } else {
        rules = {
          invoiceName: {
            required: true
          },
          invoiceCode: {
            required: true
          }
        };
        messages = {
          invoiceName: {
            required: "请输入单位名称",
          },
          invoiceCode: {
            required: "请填写纳税人识别码",
          }
        }
      }
      this._invoiceValidate = new WxValidate(rules, messages);
    },

    _initSelfpickUserFormValidate() {
      let rules = {
        name: {
          required: true
        },
        mobile: {
          required: true,
          tel: true
        }
      };
      let messages = {
        name: {
          required: "请输入姓名",
        },
        mobile: {
          required: "请输入手机号",
          tel: "请填写正确的手机号码"
        }
      }
      this._selfpickUserFormValidate = new WxValidate(rules, messages);
    }
  }
})


